class InvitationController < ApplicationController
  layout 'login'
  #include ApplicationHelper
  
  def index
    redirect_to :controller=>:welcome
  end
  
  def join
    @join = Invitation.find_by_key(params[:id])
    redirect_to :action=>:error and return if(!@join)
  end
  
  def error    
  end
  
  def add_users
    @project = Project.find(params[:id])
    emails  = params[:invite][:emails].split("\n")
    from = session['user']
    STDERR.puts emails
    name    = params[:invite][:name]
    msg     = params[:invite][:msg]
    
    # search email in the users db
    emails.each { |e|
      
      # verify if the invitation is already sent
      i = Invitation.find_by_email_and_project_id(e,@project.id)
      logger.info "invitation for #{e} already exist"
      next if(i)
      
      # try to find the invited
      u = User.find_by_email(e)
      id = if(u); u.id; else; -1;end
      logger.info "invitation id=#{id}"
      next if (u and u.projects.member?(@project.id)) # TODO: to test
      
      # generate a key
      key = ApplicationHelper.generate_key
      logger.info "key=#{key}"
      
      # create record
      i = Invitation.create(:user_id=>from.id,:name=>name, :msg=>msg, :key=>key, :email=>e, :invited_id=>id, :project_id=>@project.id)
      
      #send email
      AppMailer.deliver_invite_users(i,@project,from)
      AppMailer.deliver_alert('invitation',"#{i.to_s}")
    }
    flash[:notice] = emails.size.to_s + " email(s) sent"
    redirect_to(:controller=>:project, :action => :edit, :id=>@project)
  end
  
  def accept
    id = params[:id]
    i = Invitation.find(id)
    AppMailer.deliver_invite_result(i, "accepted")
    AppMailer.deliver_alert('invitation accepted',"#{i.to_s}")
    session['user'].accept_invitation([i]) # delete the invitation
    render(:text=>"You are now member of the project \"<a href=\"/task/select_project_index/#{i.project.id}\">#{i.project.name}</a>\"")
  end
  
  def decline
    id = params[:id]
    i = Invitation.find(id)
    AppMailer.deliver_invite_result(i, "declined")
    AppMailer.deliver_alert('invitation declined',"#{i.to_s}")
    session['user'].decline_invitation([i]) # delete the invitation
    render(:text=>"You've just declined the invitation.")
  end
end
